package com.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.entity.ChatMessage;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 聊天消息DAO接口
 */
@Mapper
public interface ChatMessageDao extends BaseMapper<ChatMessage> {

    /**
     * 根据发送者和接收者查询消息
     */
    @Select("SELECT * FROM chat_message WHERE " +
            "(sender_openid = #{senderOpenId} AND receiver_openid = #{receiverOpenId}) OR " +
            "(sender_openid = #{receiverOpenId} AND receiver_openid = #{senderOpenId}) " +
            "ORDER BY send_time DESC LIMIT #{offset}, #{limit}")
    List<ChatMessage> findBySenderAndReceiver(@Param("senderOpenId") String senderOpenId, 
                                             @Param("receiverOpenId") String receiverOpenId,
                                             @Param("offset") int offset, 
                                             @Param("limit") int limit);

    /**
     * 统计未读消息数量
     */
    @Select("SELECT COUNT(*) FROM chat_message WHERE receiver_openid = #{receiverOpenId} AND status = 'sent'")
    int countUnreadMessages(@Param("receiverOpenId") String receiverOpenId);

    /**
     * 根据用户查询最近的聊天记录
     */
    @Select("SELECT * FROM chat_message WHERE " +
            "(sender_openid = #{openId} OR receiver_openid = #{openId}) " +
            "AND id IN (" +
            "SELECT MAX(id) FROM chat_message " +
            "WHERE sender_openid = #{openId} OR receiver_openid = #{openId} " +
            "GROUP BY CASE WHEN sender_openid = #{openId} THEN receiver_openid ELSE sender_openid END" +
            ") ORDER BY send_time DESC")
    List<ChatMessage> findRecentChats(@Param("openId") String openId);
}